from datetime import datetime

from apscheduler.schedulers.background import BackgroundScheduler
from fastapi import APIRouter

from utils.FileUtil import FileUtil
from utils.MySqlUtil import MySqlUtil

router = APIRouter(
    prefix="/job",
    tags=["job"],
    responses={404: {"description": "Not found"}},
)

scheduler = BackgroundScheduler()


def create_user_item_grade_file():
    sql = 'SELECT a.user_id as userId,b.goods_id as goodsId,b.grade as grade FROM confirm_order a,confirm_order_item ' \
          'b where a.id = b.order_id '
    db = MySqlUtil()
    file_data = set()
    result_list = db.query(sql, None)
    for result in result_list:
        setData = f"{result['userId']},{result['goodsId']},{result['grade']}"
        file_data.add(setData)
    if FileUtil.create_txt(file_data, 0):
        print(f'定时生成【用户-商品-评分】矩阵文件完成：{datetime.now()}')
    else:
        print(f'定时生成【用户-商品-评分】矩阵文件失败：{datetime.now()}')


def create_user_classfiy_grade_file():
    file_data = set()
    sql = 'SELECT c.user_id,b.classify,a.grade FROM confirm_order_item a LEFT JOIN goods b ON a.goods_id = b.id LEFT ' \
          'JOIN confirm_order c ON a.order_id = c.id '
    db = MySqlUtil()
    data_list = db.query(sql, None)
    temp = {}
    for data in data_list:
        user_id = data['user_id']
        classify = data['classify']
        grade = data['grade']
        temp_key = f'{user_id},{classify}'
        if temp_key in temp:
            va = int(temp[temp_key])
            new_va = int(grade)
            if new_va > va:
                temp[temp_key] = new_va
        else:
            temp[temp_key] = grade
    for key, value in temp.items():
        s = f'{key},{value}'
        file_data.add(s)
    if FileUtil.create_txt(file_data, 1):
        print(f'定时生成【用户-分类-评分】矩阵文件完成：{datetime.now()}')
    else:
        print(f'定时生成【用户-分类-评分】矩阵文件失败：{datetime.now()}')


@router.on_event("startup")
async def app_start():
    scheduler.add_job(create_user_item_grade_file, 'interval', seconds=30)
    scheduler.add_job(create_user_classfiy_grade_file, 'interval', seconds=50)
    scheduler.start()